/**
 * Copyright (C) 2018 - 2020 https://github.com/LeeYan9
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.listener;

import com.bifrost.constant.MerchantConfigurationType;
import com.bifrost.entity.Customer;
import com.bifrost.entity.MerchantConfiguration;
import com.bifrost.entity.MerchantStore;
import com.bifrost.event.CustomerRegisterEvent;
import com.bifrost.model.TemplateData;
import com.bifrost.repository.MerchantConfigurationRepository;
import com.bifrost.service.CustomerService;
import com.bifrost.service.StoreService;
import com.bifrost.wechat.entity.WechatAccount;
import com.bifrost.wechat.service.WechatAccountService;
import com.bifrost.wechat.service.WxServiceContext;
import com.google.common.collect.Lists;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author Lee
 * Create Class on 2018/8/27
 * @com.bifrost.listener
 * @wechat-mall
 */
@Component
public class CustomerRegisterListener implements ApplicationListener<CustomerRegisterEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerRegisterListener.class);
    @Autowired
    CustomerService customerService;
    @Autowired
    WechatAccountService accountService;
    @Autowired
    MerchantConfigurationRepository configurationRepository;
    @Autowired
    WxServiceContext wxServiceContext;

    /**
     * Handle an application event.
     *
     * @param event the event to respond to
     */
    @Override
    @Async
    public void onApplicationEvent(CustomerRegisterEvent event) {
        Long customerId = event.customerId;
        String bonusPoints = event.bonusPoints;
        Customer customer = customerService.findCustomer(customerId);
        MerchantStore store = customer.getMerchantStore();
        WechatAccount account = accountService.getAccount(store.getMerchantId());
        List<MerchantConfiguration> configurations = configurationRepository.findByMerchantStoreAndTypeAndKey(store.getMerchantId(), MerchantConfigurationType.MESSAGE.name(), "REGISTER");
        if(configurations.isEmpty()){
            LOGGER.error(store.getStoreCode()+"门店没有配置模板信息");
            return;
        }

        WxMpTemplateMessage message = WxMpTemplateMessage.builder()
                .data(templateModel(customer,bonusPoints,store))
                .templateId(configurations.get(0).getValue())
                .toUser(customer.getOpenId())
                .url("").build();

        if(account!=null){
            WxMpService service = wxServiceContext.getWxServiceByAppId(account.getAppId());
            try {
                service.getTemplateMsgService().sendTemplateMsg(message);
            } catch (WxErrorException e) {
                e.printStackTrace();
                LOGGER.error("模板消息发送失败..",e);
            }
        }
    }



    public List templateModel(Customer customer , String bonusPoints , MerchantStore store){
        ArrayList<WxMpTemplateData> templateDatas = Lists.newArrayList();
        WxMpTemplateData first = new WxMpTemplateData("first", "亲爱的会员,你的会员卡有新积分到账","#173177");
        WxMpTemplateData keyword1 = new WxMpTemplateData("keyword1", customer.getLoyaltyCard(),"#173177");
        WxMpTemplateData keyword2 = new WxMpTemplateData("keyword2", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),"#173177");
        WxMpTemplateData keyword3 = new WxMpTemplateData("keyword3", "会员积分","#173177");
        WxMpTemplateData keyword4 = new WxMpTemplateData("keyword4", bonusPoints+" 积分","#173177");
        WxMpTemplateData keyword5 = new WxMpTemplateData("keyword5", customer.getBonusPoints().add(new BigInteger(bonusPoints))+" 积分","#173177");
        WxMpTemplateData remark = new WxMpTemplateData("remark", store.getStoreName(),"#173177");
        templateDatas.add(first);
        templateDatas.add(keyword1);
        templateDatas.add(keyword2);
        templateDatas.add(keyword3);
        templateDatas.add(keyword4);
        templateDatas.add(keyword5);
        templateDatas.add(remark);
        return templateDatas;
    }
}
